package com.ply.flashsalessystem.filter;

import com.alibaba.fastjson.JSONObject;
import com.ply.flashsalessystem.config.onlineCount.OnlineCount;
import com.ply.flashsalessystem.entity.result.Result;
import com.ply.flashsalessystem.exception.IdentityException;
import com.ply.flashsalessystem.utils.CrossUtils;
import com.ply.flashsalessystem.utils.JWTUtil;
import com.ply.flashsalessystem.utils.Type;
import com.ply.flashsalessystem.utils.UserUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletRequest;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * @author XiaoPan
 * date: 2022/3/24 10:47
 * <p>
 * action:  User登录
 */
@Slf4j
public class UserFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("现在进入{}过滤器中", UserFilter.class);
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        CrossUtils.cross(request, response);

        String token = request.getHeader("token");

        if (null == token || token.equals("")) {
            response.getWriter().write((JSONObject.toJSONString(Result.loginError())));
//            throw new IdentityException("没有token");
            return;
        }
        if (!JWTUtil.verifyToken(token, Type.TYPE_USER)) {
            response.getWriter().write((JSONObject.toJSONString(Result.loginError())));
            return;
        }
//         放入到 UserUtil 中去
        Map<String, Object> username = JWTUtil.getUsername(token);
        UserUtils.addUserUtils((Long)username.get("id"),(String) username.get("name"),(String) username.get("type"));

        String newToken = JWTUtil.sign(UserUtils.getUserId(),
                UserUtils.getUserName(),
                UserUtils.getUserType());

        //统计在线人数的测试
        if (Objects.equals(UserUtils.getUserType(), Type.TYPE_USER)){
            OnlineCount.updateMap(UserUtils.getUserName());
        }

        //设置响应头
        response.setHeader("token", newToken);
        log.info("成功");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

}
